/**
 * 异步上传文件
 * options = {
 * 	   url:upload_url,
 *    dataType: json_or_xml_or_plain,
 *    success: callback(data)
 * }
 */
(function($){
	$.fn.ajaxupload = function(options){
		return this.each(function(){
			if(_is_file_input(this)){				
				new AjaxFileUpload(this, options);
			}			
		});
		
		//check if the input element is file input element
		function _is_file_input(element){
			var $this = $(element);
			return $this.val() && $this.is(":file");		
		}
	};
	
	
	var counter = 0;
	function AjaxFileUpload(element, options){
		this.$element = $(element);
		this.$clone = $(element).clone(true);		
		this.options = options;
		this.upload();
	};
	
	AjaxFileUpload.prototype = {		
		upload: function(){
			var self = this;
			var id = ++counter;
			
			//create upload iframe
			var iframeId = "uploadFile-iframe-" + id;
			var formId = "uploadFile-form-" + id;
			this._create_upload_iframe_form(iframeId, formId);
			
			//create upload form			
			var $form = $("#" + formId);		
			this.$element.before(this.$clone).appendTo($form);
				
			$form.attr("action", this.options.url);
			$form.attr("target", iframeId);
			$form.submit();
			
			var $iframe = $("#" + iframeId);
			//load iframe
			$iframe.load(function(){
				//handle ajax request
				self._upload_callback($iframe[0], $form[0]);
			});
		},
		_create_upload_iframe_form: function(frameId, formId){
			var html = "<iframe id='${frameId}' name='${frameId}'  style='position:absolute; top:-9999px; left:-9999px'  src='javascript:false'/><form id='${formId}' name='${formId}' enctype='multipart/form-data' method='POST' style='position:absolute; top:-9999px; left:-9999px'></form>";
			html = html.replace(/\$\{frameId\}/g, frameId);
			html = html.replace(/\$\{formId\}/g, formId);				
			$(html).appendTo(document.body);				
		},
		
		_upload_callback: function(iframe, form){
			var responseText = "";
			if(iframe.contentWindow){
				responseText = iframe.contentWindow.document.body ? iframe.contentWindow.document.body.innerHTML : null;
            }else if(iframe.contentDocument){
				responseText = iframe.contentDocument.document.body ? iframe.contentDocument.document.body.innerHTML : null;
            }				
			
			if(responseText){					
				//去掉responeText两边可能的<pre></pre>
				var regex = /<pre.*>(.+)<\/pre>/gi;
				if(regex.test(responseText)){
					responseText = RegExp.$1;
				}
				if(this.options.dataType == 'json'){
					responseText = $.parseJSON(responseText);
				}
				
				if( this.options.success ){				
					this.options.success(responseText);
				}
			}			
			//$(iframe).remove();
			//$(form).remove();
		}		
	};
})(jQuery);